package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.iot08.common.entity.app.DevHCYAuth;
import com.iot08.common.entity.app.FamilyHCYAuth;
import com.iot08.common.entity.app.HCYAuthLog;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.HttpReq;
import com.iot08.common.utils.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author weichao 1299101858@qq.com
 * @version 1.0
 * @date 12/16/22 6:37 PM
 */
@Slf4j
@Service
public class FamilyHCYAuthService extends BaseService<FamilyHCYAuth> {

    @Resource
    private DevHCYAuthService devHCYAuthService;

    @Resource
    private HCYAuthLogService hcyAuthLogService;

    @Resource
    private HCYPhoneCloudService hcyPhoneCloudService;

    public String getAppID(FamilyHCYAuth familyHCYAuth){
        JSONObject item = devHCYAuthService.getHCY_ConfigArr().getJSONObject(familyHCYAuth.getProject_type());
        return item.getString("appId");
//        if(familyHCYAuth.getProject_type() == 0){
//            //LY_K12
//            return devHCYAuthService.HCY_LYY_LYK12APPID;
//        }else{
//            //LY_K20
//            return devHCYAuthService.HCY_LYY_LYK20APPID;
//        }
    }

    public String getAppKey(FamilyHCYAuth familyHCYAuth){
        JSONObject item = devHCYAuthService.getHCY_ConfigArr().getJSONObject(familyHCYAuth.getProject_type());
        return item.getString("appKey");
//        if(familyHCYAuth.getProject_type() == 0){
//            //LY_K12
//            return devHCYAuthService.HCY_LYY_LYK12AppKey;
//        }else{
//            //LY_K20
//            return devHCYAuthService.HCY_LYY_LYK20AppKey;
//        }
    }

    public String getAppSecret(FamilyHCYAuth familyHCYAuth){
        JSONObject item = devHCYAuthService.getHCY_ConfigArr().getJSONObject(familyHCYAuth.getProject_type());
        return item.getString("appSecret");
//        if(familyHCYAuth.getProject_type() == 0){
//            //LY_K12
//            return devHCYAuthService.HCY_LYY_LYK12AppSecret;
//        }else{
//            //LY_K20
//            return devHCYAuthService.HCY_LYY_LYK20AppSecret;
//        }
    }

    public String getAppTitle(FamilyHCYAuth familyHCYAuth){
        JSONObject item = devHCYAuthService.getHCY_ConfigArr().getJSONObject(familyHCYAuth.getProject_type());
        return item.getString("ident");
//        if(familyHCYAuth.getProject_type() == 0){
//            //LY_K12
//            //岭雁科技云相册LYK12
//            return "LY_K12";
//        }else{
//            //LY_K20
//            //岭雁科技云相册LYK20
//            return "LY_K20";
//        }
    }

    /**
     * 家长 和彩云相册token 有效期内刷新Token
     * @param imei
     * @param family_auth_uuid 当前家长真正请求的uuid
     * @param familyHCYAuth
     * @time: 1/6/23 11:52 AM
     * @author: Weichao
     * @version 1.0
     */
    public String familyHCYRefreshToken(String imei, String family_auth_uuid, FamilyHCYAuth familyHCYAuth){
        //未失效, 需检查一下, 鉴权的失效时间
        String hcy_accesstoken = familyHCYAuth.getHcy_accesstoken();
        Long hcy_accesstoken_expiry = familyHCYAuth.getHcy_accesstoken_expiry();
        Long nowTime = DateUtil.nowTimestampToLong();
        if ((hcy_accesstoken_expiry - nowTime) < devHCYAuthService.checkTokenExpiryTime){
            log.info("imei:{} 刷新云相册 家长({})的原token: {}, 原token的失效时间:{} 临期检查时间:{}",
                    imei, family_auth_uuid, hcy_accesstoken, hcy_accesstoken_expiry, devHCYAuthService.checkTokenExpiryTime);
            JSONObject jsonParameter = new JSONObject();

            jsonParameter.put("appId", this.getAppID(familyHCYAuth));
            jsonParameter.put("appSecret", this.getAppSecret(familyHCYAuth));

            jsonParameter.put("refreshToken", hcy_accesstoken);

            String result = HttpReq.sendPostJson(devHCYAuthService.HCYRefreshTokenURL, jsonParameter.toString());
            JSONObject resultOB = JSONObject.parseObject(result);
                        /*
                        expiresIn: 失效时间 (单位小时)
                        {"code":0,"totalRows":0,"message":"成功","data":{"expiresIn":168,"accessToken":"XXXX"}}
                        */
            if(resultOB.getInteger("code") == 0){
                JSONObject data = resultOB.getJSONObject("data");
                String newToken = data.getString("accessToken");
                //单位是小时
                Integer newTokenExpiresIn = data.getInteger("expiresIn");
                Update update = new Update();
                // hcy_accesstoken
                // hcy_accesstoken_expiry
                long newTokenExpires = nowTime + newTokenExpiresIn * 3600;
                // hcy_accesstoken_update
                nowTime = DateUtil.nowTimestampToLong();
                update.set("hcy_accesstoken", newToken);
                update.set("hcy_accesstoken_expiry", newTokenExpires);
                update.set("hcy_accesstoken_update", nowTime);
                this.updateById(family_auth_uuid, update);
                familyHCYAuth.setHcy_accesstoken(newToken);
                familyHCYAuth.setHcy_accesstoken_expiry(newTokenExpires);
                familyHCYAuth.setHcy_accesstoken_update(new Date());
                this.save(familyHCYAuth);
                log.info("imei:{}, 刷新云相册 家长({})token成功,newToken:{} 新token失效时间戳:{} ",
                        imei, family_auth_uuid, newToken, newTokenExpires);
                return newToken;
            }else {
                log.error("imei:{} 刷新云相册 家长({})token失败 resultOB:{}", imei, family_auth_uuid, resultOB);
                return null;
            }
        }else{
            //家长token有效,无需刷新
            log.info("imei:{} 家长({})token有效,无需刷新 token失效时间戳:{} ", imei, family_auth_uuid, hcy_accesstoken_expiry);
            return hcy_accesstoken;
        }
    }


    /**
     * 家长拥有 有效token后 获取单点登陆过后的 和彩云H5云相册 地址
     * @param devHCYAuth
     * @param familyHCYAuth
     * @param isQType 0:Web 1:Android 2:iOS
     * @time: 1/3/23 5:20 PM
     * @author: Weichao
     * @version 1.0
     */
    public String getAuthHCY_H5URL(DevHCYAuth devHCYAuth, FamilyHCYAuth familyHCYAuth, int isQType){
        Map<String, String> headers = new HashMap<>();
        JSONObject signOnAuthParam = new JSONObject();
        headers.put("appid", this.getAppID(familyHCYAuth));
        headers.put("secretkey", this.getAppSecret(familyHCYAuth));
//        switch (isQType){
//            case 0:
//                signOnAuthParam.put("channelId", devHCYAuthService.HCY_Web_CHANNELID);
//                break;
//            case 1:
//                signOnAuthParam.put("channelId", devHCYAuthService.HCY_Android_CHANNELID);
//                break;
//            case 2:
//                signOnAuthParam.put("channelId", devHCYAuthService.HCY_IOS_CHANNELID);
//                break;
//        }
        // H5 的请求固定用 硬件类型:10012
        signOnAuthParam.put("channelId", devHCYAuthService.HCY_Hardware_CHANNELID);
        signOnAuthParam.put("token", familyHCYAuth.getHcy_accesstoken());
        signOnAuthParam.put("tokenType", "2");
        //TODO H5的登录连接(测试服)
        String hcyAlbum_h5URL = devHCYAuthService.HCYAlbum_H5URL;//需要替换参数
        hcyAlbum_h5URL = hcyAlbum_h5URL.replace("{albumName}","lyalbumwap");
        hcyAlbum_h5URL = hcyAlbum_h5URL.replace("{familyId}", devHCYAuth.getCloudID());
        hcyAlbum_h5URL = hcyAlbum_h5URL.replace("{albumId}", devHCYAuth.getAlbumld());
        hcyAlbum_h5URL = hcyAlbum_h5URL.replace("{source}","app-embed-ly");
        hcyAlbum_h5URL = hcyAlbum_h5URL.replace("{channel}", devHCYAuthService.h5platformChannelID);
        signOnAuthParam.put("redirectUrl", hcyAlbum_h5URL);


        String hcyAuthResult = HttpReq.sendPostJson(devHCYAuthService.HCYSignOnAuthURL, signOnAuthParam.toString(), headers);
        JSONObject hcyAuthResultOB = JSONObject.parseObject(hcyAuthResult);
        /*
        {
            "code": 0,
            "message": "成功",
            "data": "https://yun.139.com/XXXX"
        }
        */
        if(hcyAuthResultOB.getInteger("code") == 0){
            return hcyAuthResultOB.getString("data");
        }else{
            log.error("imei:{} 云相册 家长({}) 单点登录失败:{} post 参数:{} headers:{}",devHCYAuth.getId(), familyHCYAuth.getId(), hcyAuthResultOB, signOnAuthParam.toString(), JSONObject.toJSON(headers));
            return null;
        }
    }

    /**
     * 检查用户是否在家庭云中 其他: 其他错误(移动云盘返回的) -3:云相册不存在,可能是家庭群被删了 -1: accesstoken失效  0:不在其中  1:在其中
     * @param familyHCYAuth
     * @param cloudId
     * @param albumId
     * @param imei
     * @param isQType 0:Web 1:Android 2:iOS
     * @time: 1/3/23 5:19 PM
     * @author: Weichao
     * @version 1.0
     */
    public int getThisFamilyIsInHCYAlbum(FamilyHCYAuth familyHCYAuth, String cloudId, String albumId, String imei, int isQType){
        //queryCloudPhoto

        Map<String, String> headers = new HashMap<>();
        JSONObject queryCloudPhotoParam = new JSONObject();
        headers.put("appid", this.getAppID(familyHCYAuth));
        headers.put("secretKey", this.getAppSecret(familyHCYAuth));
        headers.put("accessToken", familyHCYAuth.getHcy_accesstoken());
        headers.put("deviceid", familyHCYAuth.getId().split("&")[0]);
        switch (isQType){
            case 0:
                headers.put("channelid", devHCYAuthService.HCY_Web_CHANNELID);
                break;
            case 1:
                headers.put("channelid", devHCYAuthService.HCY_Android_CHANNELID);
                break;
            case 2:
                headers.put("channelid", devHCYAuthService.HCY_IOS_CHANNELID);
                break;
        }
        queryCloudPhotoParam.put("cloudID", cloudId);
        queryCloudPhotoParam.put("photoID", albumId);
        queryCloudPhotoParam.put("photoType", "0"); //仅普通相册

        String queryCloudPhotoResult = HttpReq.sendPostJson(devHCYAuthService.HCYChectCloudPhoto, queryCloudPhotoParam.toString(), headers);
        JSONObject queryCloudPhotoResultOB = JSONObject.parseObject(queryCloudPhotoResult);
        /* 返回示例
        {
            "code": 0,
            "message": "成功",
            "data": {
                "cloudPhotoList": [
                    {
                        "commonAccountInfo": {
                            "accountType": "1",
                            "account": "wFxzaOvWlOM0gPSVt/+KRA=="
                        },
                        "createTime": "20210712162118",
                        "cloudID": "f9629bcd967a4854be05df5338ef34cc",
                        "photoType": 0,
                        "photoID": "zF11lfH67009004202107121626350hc",
                        "theme": 0,
                        "photoName": "我的新相册",
                        "lastUpdateTime": "20210712162704"
                    }
                ],
                "totalCount": 1
            }
        }
        */
        if(queryCloudPhotoResultOB.getInteger("code") == 0) {
            return 1; //在其中
        }else if(queryCloudPhotoResultOB.getInteger("code") == 1809011501){
            log.info("imei:{} 家长ID:{} 检查和彩云相册cloudId :{} 用户非家庭云成员 :{}", imei, familyHCYAuth.getId(), cloudId, queryCloudPhotoResult);
            return 0; //不在其中
        }else if(queryCloudPhotoResultOB.getInteger("code") == 20011 ||
                queryCloudPhotoResultOB.getInteger("code") == 1809111401){
            //(家庭云鉴权失败), 检查和彩云相册的权限失败 :{"code":1809111401,"data":{},"message":"Authorization Failed!","totalRows":0}
            //accesstoken无效！ 家长需要重新授权登录
            //accesstoken失效: {"code":20011,"message":"accesstoken无效！","totalRows":0}
            log.info("imei:{} 家长ID:{} accesstoken无效！:{} 家长需要重新授权登录", imei, familyHCYAuth.getId(), queryCloudPhotoResult);
            return -1;
        }else if(queryCloudPhotoResultOB.getInteger("code") == 1809012303){
            //当前 云相册 不存在, 可能是家庭群被删了, 清除和彩云相册 授权表(DevHCYAuth)的cloudId 和 albumId 的记录, 清除 手机号<==>云相册 (HCYPhoneCloud) 的记录
            log.info("imei:{} 家长ID:{} 检查和彩云相册cloudId :{} 当前 云相册 不存在, 可能是家庭群被删了 :{}", imei, familyHCYAuth.getId(), cloudId, queryCloudPhotoResult);
            DevHCYAuth devHCYAuth = devHCYAuthService.findById(imei);
            devHCYAuth.setDev_accesstoken(null);
            devHCYAuth.setDev_accesstoken_update(null);
            devHCYAuth.setDev_accesstoken_expiry(null);
            devHCYAuth.setAlbumld(null);
            devHCYAuth.setCloudID(null);
            devHCYAuthService.save(devHCYAuth);
            hcyPhoneCloudService.delById(devHCYAuth.getPhone());
            log.info("imei:{} 家长ID:{} 清除异常的 相册ID缓存 成功 cloudId :{} 对应设备的phone:{}", imei, familyHCYAuth.getId(), cloudId, devHCYAuth.getPhone());
            return -3;
        }else{
            log.error("imei:{} 家长ID:{} 检查和彩云相册的权限失败 :{}", imei, familyHCYAuth.getId(), queryCloudPhotoResult);
            return queryCloudPhotoResultOB.getInteger("code");
        }
    }

    /**
     * 自动加入云相册  -2:其他错误 -1: accesstoken失效  0: 成功
     * @param devHCYAuth
     * @param familyHCYAuth
     * @param imei
     * @param isQType 0:Web 1:Android 2:iOS
     * @time: 1/3/23 5:17 PM
     * @author: Weichao
     * @version 1.0
     */
    public int postFamilyAutoJoinCloudId(DevHCYAuth devHCYAuth, FamilyHCYAuth familyHCYAuth, String imei, int isQType){
        //inviteFamilyMember 邀请用户加入家庭云（链接模式）

        Map<String, String> headers = new HashMap<>();
        JSONObject inviteFamilyMemberParam = new JSONObject();
        headers.put("appid", devHCYAuthService.getAppID(devHCYAuth));
        headers.put("secretKey", devHCYAuthService.getAppSecret(devHCYAuth));
        headers.put("accessToken", devHCYAuth.getDev_accesstoken());
        headers.put("deviceid", devHCYAuth.getId());
        switch (isQType){
            case 0:
                headers.put("channelid", devHCYAuthService.HCY_Web_CHANNELID);
                break;
            case 1:
                headers.put("channelid", devHCYAuthService.HCY_Android_CHANNELID);
                break;
            case 2:
                headers.put("channelid", devHCYAuthService.HCY_IOS_CHANNELID);
                break;
        }
        inviteFamilyMemberParam.put("cloudID", devHCYAuth.getCloudID());


        String inviteFamilyMemberResult = HttpReq.sendPostJson(devHCYAuthService.HCYInviteFamilyMember, inviteFamilyMemberParam.toString(), headers);
        JSONObject inviteFamilyMemberResultOB = JSONObject.parseObject(inviteFamilyMemberResult);
        if(inviteFamilyMemberResultOB.getInteger("code") == 0) {
            //添加日志记录
            HCYAuthLog hcyAuthLog = new HCYAuthLog();
            hcyAuthLog.setId(UUIDGenerator.generate());
            hcyAuthLog.setImei(imei);
            hcyAuthLog.setFamilyUUID(familyHCYAuth.getId());
            hcyAuthLog.setFamilyPhone(familyHCYAuth.getPhone());
            //授权类型:
            // 0:家长授权 1:设备自己登录授权 2:设备邀请加入云相册
            // 3:家长自己登录授权 4:家长加入云相册
            hcyAuthLog.setType(2);
            hcyAuthLog.setCreatDate(new Date());
            hcyAuthLogService.save(hcyAuthLog);

            //取到邀请码后 调用确认邀请接口
            /*
            {
                "code": 0,
                "message": "成功",
                 "data":{
                    "validePeriod": "259200",
                    "invitationCode": "202112141649006727847514714",
                    "invitationURL": "https://c.139jxx.com/w/#/invitation?type=2&source=2"
                }
            }
            */
            String invitationCode = inviteFamilyMemberResultOB.getJSONObject("data").getString("invitationCode");
            //confirmInvitation 确认邀请
            headers.put("accessToken", familyHCYAuth.getHcy_accesstoken());
            headers.put("deviceid", familyHCYAuth.getId().split("&")[0]);
            JSONObject confirmInvitationParam = new JSONObject();
            confirmInvitationParam.put("invitationCode", invitationCode);
            String confirmInvitationResult = HttpReq.sendPostJson(devHCYAuthService.HCYConfirmInvitation, confirmInvitationParam.toString(), headers);
            JSONObject confirmInvitationResultOB = JSONObject.parseObject(confirmInvitationResult);

            if(confirmInvitationResultOB.getInteger("code") == 0) {
                //添加日志记录
                HCYAuthLog hcyAuthLog1 = new HCYAuthLog();
                hcyAuthLog1.setId(UUIDGenerator.generate());
                hcyAuthLog1.setImei(imei);
                hcyAuthLog1.setFamilyUUID(familyHCYAuth.getId());
                hcyAuthLog1.setFamilyPhone(familyHCYAuth.getPhone());
                //授权类型:
                // 0:家长授权 1:设备自己登录授权 2:设备邀请加入云相册
                // 3:家长自己登录授权 4:家长加入云相册
                hcyAuthLog1.setType(4);
                hcyAuthLog1.setCreatDate(new Date());
                hcyAuthLogService.save(hcyAuthLog1);
                return 0; //加入成功
            }else if (confirmInvitationResultOB.getInteger("code") == 2020149) {
                //{"code":2020149,"message":"你已在该圈子中","totalRows":0,"data":{}}
                return 0;
            }else {
                log.error("imei:{} 家长:{} 携带邀请码:{}, 确认加入云相册失败:{}", imei, familyHCYAuth.getId(), invitationCode, confirmInvitationResult);
                return -2; //其他错误
            }

        }else if(inviteFamilyMemberResultOB.getInteger("code") == 20011){
            //accesstoken无效！ 家长需要重新授权登录
            //accesstoken失效: {"code":20011,"message":"accesstoken无效！","totalRows":0}

            log.error("imei:{} 设备发起邀请请求 家长({}) 加入云相册失败:{}", imei, familyHCYAuth.getId(), inviteFamilyMemberResult);
            return -1;
        }else{
            log.error("imei:{} 设备发起邀请请求 家长({}) 加入云相册失败:{}", imei, familyHCYAuth.getId(), inviteFamilyMemberResult);
            return -2;
        }

    }
}
